const Message = require('../models/Message');
const { buildXML } = require('../utils/xmlHelper');
const userService = require('../services/userService');
const wechatService = require('../services/wechatService');

// 处理微信消息
const handleMessage = async (req, res) => {
  const message = req.wechat;
  
  try {
    // 保存消息到数据库
    const savedMessage = new Message(message);
    await savedMessage.save();
    
    // 处理不同类型消息
    switch (message.MsgType) {
      case 'text':
        await handleTextMessage(message, res);
        break;
      case 'event':
        await handleEventMessage(message, res);
        break;
      case 'image':
        await handleImageMessage(message, res);
        break;
      case 'voice':
        await handleVoiceMessage(message, res);
        break;
      default:
        await replyMessage(message, res, '暂不支持此类型消息');
    }
  } catch (error) {
    console.error('处理消息失败:', error);
    res.status(500).send('Server Error');
  }
};

// 处理文本消息
async function handleTextMessage(message, res) {
  const content = message.Content.trim();
  
  // 根据关键词回复
  let replyContent = '';
  switch (content) {
    case '帮助':
      replyContent = '请输入以下关键词获取帮助:\n1. 帮助 - 查看帮助信息\n2. 活动 - 查看最新活动\n3. 联系 - 获取联系方式';
      break;
    case '活动':
      replyContent = '最新活动:\n1. 新用户注册立减20元\n2. 推荐好友得优惠券\n3. 周末特惠专场';
      break;
    case '联系':
      replyContent = '客服电话: 400-123-4567\n工作时间: 9:00-18:00\n微信公众号: 您的公众号名称';
      break;
    default:
      replyContent = `您说的是: ${content}\n如需帮助，请输入"帮助"查看可用命令`;
  }
  
  await replyMessage(message, res, replyContent);
}

// 处理事件消息
async function handleEventMessage(message, res) {
  switch (message.Event) {
    case 'subscribe':
      await handleSubscribeEvent(message, res);
      break;
    case 'unsubscribe':
      await handleUnsubscribeEvent(message, res);
      break;
    case 'CLICK':
      await handleClickEvent(message, res);
      break;
    default:
      await replyMessage(message, res, '欢迎关注我们！');
  }
}

// 处理关注事件
async function handleSubscribeEvent(message, res) {
  // 同步用户信息
  await userService.syncUser(message.FromUserName);
  
  const replyContent = '感谢您的关注！\n请输入"帮助"查看可用功能。';
  await replyMessage(message, res, replyContent);
}

// 处理取消关注事件
async function handleUnsubscribeEvent(message, res) {
  // 更新用户订阅状态
  const user = await userService.getUser(message.FromUserName);
  if (user) {
    user.subscribe = false;
    await user.save();
  }
  
  // 不需要回复取消关注事件
  res.send('success');
}

// 处理菜单点击事件
async function handleClickEvent(message, res) {
  let replyContent = '';
  
  switch (message.EventKey) {
    case 'V1001_TODAY_RECOMMEND':
      replyContent = '今日推荐:\n1. 特价商品A - 原价100元，现价79元\n2. 新品上市B - 限时8折优惠\n3. 热销商品C - 买一送一';
      break;
    case 'V1001_CONTACT_US':
      replyContent = '客服电话: 400-123-4567\n工作时间: 9:00-18:00\n微信公众号: 您的公众号名称';
      break;
    default:
      replyContent = '点击了菜单: ' + message.EventKey;
  }
  
  await replyMessage(message, res, replyContent);
}

// 处理图片消息
async function handleImageMessage(message, res) {
  const replyContent = `收到图片消息\nMediaId: ${message.MediaId}\n图片已保存，我们的客服会尽快处理`;
  await replyMessage(message, res, replyContent);
}

// 处理语音消息
async function handleVoiceMessage(message, res) {
  const replyContent = `收到语音消息\n识别结果: ${message.Recognition || '未能识别'}`;
  await replyMessage(message, res, replyContent);
}

// 回复消息
async function replyMessage(message, res, content) {
  const reply = {
    ToUserName: message.FromUserName,
    FromUserName: message.ToUserName,
    CreateTime: Math.floor(Date.now() / 1000),
    MsgType: 'text',
    Content: content
  };
  
  const xml = buildXML(reply);
  res.set('Content-Type', 'text/xml');
  res.send(xml);
}

// 获取消息列表
const getMessages = async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;
    
    const messages = await Message.find()
      .sort({ CreateTime: -1 })
      .skip(skip)
      .limit(limit);
    
    const total = await Message.countDocuments();
    
    res.json({
      success: true,
      data: messages,
      pagination: {
        page,
        limit,
        total,
        pages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取消息列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取消息列表失败'
    });
  }
};

module.exports = {
  handleMessage,
  getMessages
};